import { parse } from '@babel/parser';
import generate from '@babel/generator';
import traverse from '@babel/traverse';

export default function localeFilter({ includes = [], excludes = [] }) {
  return {
    name: 'vite-plugin-locale-filter',

    transform: (code, id) => {
      if (/\.(ya?ml)$/.test(id)) {
        const ast = parse(code, {
          sourceType: 'module',
        });

        traverse.default(ast, {
          VariableDeclarator(path) {
            const properties = path.node.init.properties;

            path.node.init.properties = properties.filter(prop => {
              const key = prop.key && prop.key.value;
              return includes.includes(key) && !excludes.includes(key);
            });
          },
        });

        const { code: output } = generate.default(ast);

        return {
          code: output,
          map: { mappings: '' },
        };
      }
    },
  }
}
